package com.rickpan.controller;

import com.rickpan.common.Result;
import com.rickpan.entity.FileInfo;
import com.rickpan.service.TrashService;
import com.rickpan.utils.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 回收站管理控制器
 * 
 * @author RickPan Team
 * @since 2025-01-07
 */
@RestController
@RequestMapping("/api/trash")
public class TrashController {
    
    private static final Logger logger = LoggerFactory.getLogger(TrashController.class);
    
    @Autowired
    private TrashService trashService;
    
    /**
     * 获取回收站文件列表
     * GET /api/trash/files
     */
    @GetMapping("/files")
    public Result<Page<FileInfo>> getTrashFiles(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size,
            @RequestParam(defaultValue = "deletedAt") String sortBy,
            @RequestParam(defaultValue = "desc") String sortDir) {
        
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            logger.info("用户 {} 获取回收站文件列表: page={}, size={}", userId, page, size);
            
            // 创建排序对象
            Sort sort = Sort.by(sortDir.equalsIgnoreCase("desc") ? 
                Sort.Direction.DESC : Sort.Direction.ASC, sortBy);
            Pageable pageable = PageRequest.of(page, size, sort);
            
            Page<FileInfo> trashFiles = trashService.getTrashFiles(userId, pageable);
            
            return Result.success(trashFiles);

        } catch (Exception e) {
            logger.error("获取回收站文件列表失败", e);
            return Result.error("获取回收站文件列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取回收站统计信息
     * GET /api/trash/stats
     */
    @GetMapping("/stats")
    public Result<TrashService.TrashStats> getTrashStats() {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            logger.info("用户 {} 获取回收站统计信息", userId);
            
            TrashService.TrashStats stats = trashService.getTrashStats(userId);
            
            return Result.success(stats);

        } catch (Exception e) {
            logger.error("获取回收站统计信息失败", e);
            return Result.error("获取回收站统计信息失败: " + e.getMessage());
        }
    }
    
    /**
     * 还原文件
     * POST /api/trash/restore
     */
    @PostMapping("/restore")
    public Result<String> restoreFiles(@RequestBody RestoreRequest request) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            logger.info("用户 {} 还原文件: fileIds={}, restoreToRoot={}", 
                       userId, request.getFileIds(), request.isRestoreToRoot());
            
            trashService.restoreFiles(userId, request.getFileIds(), request.isRestoreToRoot());
            
            return Result.success("文件还原成功");

        } catch (Exception e) {
            logger.error("还原文件失败: {}", request.getFileIds(), e);
            return Result.error("还原文件失败: " + e.getMessage());
        }
    }
    
    /**
     * 彻底删除文件
     * DELETE /api/trash/permanent
     */
    @DeleteMapping("/permanent")
    public Result<String> permanentDeleteFiles(@RequestBody PermanentDeleteRequest request) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            logger.info("用户 {} 彻底删除文件: fileIds={}", userId, request.getFileIds());
            
            trashService.permanentDeleteFiles(userId, request.getFileIds());
            
            return Result.success("文件彻底删除成功");

        } catch (Exception e) {
            logger.error("彻底删除文件失败: {}", request.getFileIds(), e);
            return Result.error("彻底删除文件失败: " + e.getMessage());
        }
    }
    
    /**
     * 清空回收站
     * DELETE /api/trash/empty
     */
    @DeleteMapping("/empty")
    public Result<String> emptyTrash() {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            logger.info("用户 {} 清空回收站", userId);
            
            trashService.emptyTrash(userId);
            
            return Result.success("回收站清空成功");

        } catch (Exception e) {
            logger.error("清空回收站失败", e);
            return Result.error("清空回收站失败: " + e.getMessage());
        }
    }
    
    /**
     * 还原请求DTO
     */
    public static class RestoreRequest {
        private List<Long> fileIds;
        private boolean restoreToRoot = false;
        
        public List<Long> getFileIds() {
            return fileIds;
        }
        
        public void setFileIds(List<Long> fileIds) {
            this.fileIds = fileIds;
        }
        
        public boolean isRestoreToRoot() {
            return restoreToRoot;
        }
        
        public void setRestoreToRoot(boolean restoreToRoot) {
            this.restoreToRoot = restoreToRoot;
        }
    }
    
    /**
     * 彻底删除请求DTO
     */
    public static class PermanentDeleteRequest {
        private List<Long> fileIds;
        
        public List<Long> getFileIds() {
            return fileIds;
        }
        
        public void setFileIds(List<Long> fileIds) {
            this.fileIds = fileIds;
        }
    }
}
